package org.clipjoint.controller;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.val;
import org.clipjoint.entity.User;
import org.clipjoint.entity.dto.CommentDto;
import org.clipjoint.entity.Comment;
import org.clipjoint.service.CommentAdminService;
import org.clipjoint.service.impl.CommentAdminServiceImpl;
import org.clipjoint.vo.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 图片验证码控制器
 *
 * @author
 * date: 2021-1-11
 */
@WebServlet("/comment")
public class CommentAdminController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private CommentAdminService commentService = new CommentAdminServiceImpl();

    @SneakyThrows
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        switch (method) {
            //
            case "list":
                list(request, response);
                break;
            //批量删除
            case "deleteAll":
                deleteAll(request, response);
                break;
            //详情
            case "detail":
                detail(request, response);
                break;
            //删除一条数据
            case "del":
                del(request, response);
                break;
//            case "show":
//                show(request, response);
//                break;
            case "usercomment":
                usercomment(request, response);
                break;
        }

    }

    private void usercomment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Long gameid = Long.valueOf(request.getParameter("gameid"));
        Long user_id = Long.valueOf(request.getParameter("user_id"));
        String t1comment = request.getParameter("t1");
        int result= 0;
        try {
            result = commentService.add(Comment.builder().game_id(gameid).user_id(user_id).content(t1comment).build());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (result != 0){
            response.sendRedirect(request.getContextPath()+"/game/detail.jsp");
        }
    }

//    private void show(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
//
//        Long gameid = Long.valueOf(request.getParameter("gameid"));
//
//        List<Comment> comment =commentService.show(gameid);
//
//
////        request.getSession().setAttribute("comment",comment);
//        response.getWriter().print(JsonResult.builder().code(0).build().toJsonString());
//
//    }

    private void detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取帖子id
        Long id = Long.valueOf(request.getParameter("id"));

        // 根据id查询帖子信息
        Comment comment = null;

        try {
            comment = commentService.getOneById(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 转发到详情页面
        request.setAttribute("comment", comment);
        request.getRequestDispatcher("/comment/detail.jsp").forward(request, response);
    }

    private void del(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取id
        Long id = Long.valueOf(request.getParameter("id"));
        int result = 0;
        try {
            result = commentService.del(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        if (result == 1) {
            response.getWriter().print(JsonResult.builder().code(0).msg("删除成功").build().toJsonString());
        } else {
            response.getWriter().print(JsonResult.builder().code(1).msg("删除失败").build().toJsonString());
        }
    }

    private void deleteAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取id数组的json字符串
        String idsJSON = request.getParameter("ids");
        //将json字符串转为List集合
        List<Long> ids = JSON.parseArray(idsJSON, Long.class);

        //调用service删除所有数据
        int result = commentService.deleteAll(ids);
        if (ids.size() == result) {
            response.getWriter().print(JsonResult.builder().code(0).msg("全部删除成功").build().toJsonString());
        } else if (result != 0) {
            response.getWriter().print(JsonResult.builder().code(0).msg("成功删除" + result + "条，失败" + (ids.size() - result) + "条").build().toJsonString());
        } else {
            response.getWriter().print(JsonResult.builder().code(1).msg("删除失败").build().toJsonString());
        }


    }

    //获取用户信息列表
    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取分页参数
        Integer page = Integer.valueOf(request.getParameter("page"));
        Integer limit = Integer.valueOf(request.getParameter("limit"));

        //获取排序参数和排序方式
        String orderField = request.getParameter("orderField");
        String orderType = request.getParameter("orderType");

        //获取查询条件
        String name = request.getParameter("name");
        //封装dto
        CommentDto commentDto = CommentDto.builder()
                .page(page).limit(limit)
                .orderField(orderField)
                .orderType(orderType)
                .name(name)
                .build();

        String createTimeRange = request.getParameter("createTimeRange");
        if (createTimeRange != null) {
            String[] createTimeArray = createTimeRange.split(" - ");
            try {
                commentDto.setCreateTimeStart(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeArray[0]));
                commentDto.setCreateTimeEnd(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeArray[1]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //调用service获取用户数据
        List<Comment> list = null;
        try {
            list = commentService.list(commentDto);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //调用service获取贴子总数据量
        Long count = null;

        try {
            count = commentService.count(commentDto);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //判断结果
        if (list == null || count == null) {
            response.getWriter().print(JsonResult.builder().code(1).msg("查询错误").build().toJsonString());
            return;
        }
        //封装结果返回
        response.getWriter().print(JsonResult.builder().code(0).count(count).data(list).build().toJsonString());


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
